package org.company.saturn.hadoop.fs;

import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Options;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.SequenceFile.Writer.Option;
import org.apache.hadoop.io.Text;

public class FileUtils {
    private static FileSystem fs;
    private static Configuration config;
    
    static {
        config = new Configuration();
        try {
            fs = FileSystem.get(config);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    public static String get(String name) {
        return config.get(name);
    }
    
    public static void cat(String uri,OutputStream out) throws IOException {
        Path path = new Path(uri); 
        IOUtils.copy(fs.open(path), out);
    }
    
    public static FileStatus getStatus(String uri) throws IllegalArgumentException, IOException {
    	return fs.getFileStatus(new Path(uri));
    }
    
    public static void sequenceFileWrite(String uri,List<String> list) throws IOException {
    	Path path = new Path(uri);
    	SequenceFile.Writer writer = SequenceFile.createWriter(fs,config,path,IntWritable.class,Text.class);
    	IntWritable key = new IntWritable();
    	Text value = new Text();
    	for(int i = 0 ; i < list.size() ; i++) {
    		key.set(i);
    		value.set(list.get(i));
    		writer.append(key, value);
    	}
    	IOUtils.closeQuietly(writer);
    }
}
